<!-- 物流线路 - 表单编辑页面 -->
<template>
  <div class="page-container">

    <!-- title -->
    <div class="page-content-title">
      <!--      当前位置：新增保险产品-->
      <!--      {{$tt('label_current_position')}}：{{ $tt('label_pms_add_new_insruance_product') }}-->
    </div>

    <el-form ref="formEl" :model="formValue" label-width="130px" class="common-form-panel-div">

      <!-- 产品基础信息 -->
      <ex_header_spiler :title="$tt('label_pms_product_base_info')"></ex_header_spiler>
      <el-row style="margin-top: 20px;">
        <el-col>
          <!-- 产品名称 -->
          <el-form-item :label="$tt('label_pms_product_name')">
            <el-input v-model="formValue.productName" :disabled="isEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 产品编码 -->
          <el-form-item :label="$tt('label_pms_product_code')">
            <el-input v-model="formValue.productCode" :disabled="isEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <!-- 产品描述 -->
          <el-form-item :label="$tt('label_pms_description')">
            <el-input v-model="formValue.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <!-- 供应商产品 -->
          <el-form-item :label="$tt('label_pms_supply_product')">

            <el-checkbox-group v-model="formValue.checkedSupplyProductIds">
              <el-checkbox v-for="(item, index) in supplyArr" :label="item.id" :key="index">{{
                  item.productName
                }}
              </el-checkbox>
            </el-checkbox-group>

          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2">
          <!-- 禁止投保 sku 类目 -->
          <el-form-item :label="$tt('label_pms_disabled_sku_cates')">

            <div style="display: flex; line-height: 42px;">
              <!-- sku 类目 -->
              <div style="width:600px; margin-right: 10px; text-align: center; ">
                {{ $tt('label_pms_insurrance_sku_cates') }}
              </div>
              <div style="width: 90px;  margin-right: 10px;  text-align: center; ">
                <!-- 添加 -->
                <el-button size="medium" @click="formValue.disableSkuCategoryIds.push([])">{{ $tt('label_add') }}
                </el-button>
              </div>
            </div>

            <div style="display: flex; line-height: 42px;" v-for="(item, index) in formValue.disableSkuCategoryIds"
                 :index="'cascader_' + index">
              <div style="width: 600px;  margin-right: 10px; ">

                <el-cascader
                    style="width: 100%;"
                    v-model="formValue.disableSkuCategoryIds[index]"
                    :options="categoryArray"
                    :props="{ label: 'name', value: 'id', 'checkStrictly': true }"></el-cascader>

              </div>
              <div style="width: 90px;  margin-right: 10px;  text-align: center; color: #666; cursor: pointer; ">
                <!-- 删除 -->
                <ex-confirm-button :label="$tt('label_delete')"
                                   @afterOperationDone="formValue.disableSkuCategoryIds.splice(index, 1)"></ex-confirm-button>
              </div>
            </div>

          </el-form-item>
        </el-col>
      </el-row>

      <!-- 产品费用信息 -->
      <ex_header_spiler title="标准价卡"></ex_header_spiler>
      <div style="position: relative;">

        <!-- 添加价卡版本 -->
        <el-button @click="adTabConfig" style="position: absolute;  top: -32px; right: 20px; z-index: 999; "
                   icon="el-icon-plus">添加价卡版本
        </el-button>

        <ex-button-delete
            style="position: absolute;  top: 60px; left: 420px; z-index: 999; "
            v-if=" formValue.standardPriceVersions && formValue.standardPriceVersions.length>0 && activeName != getTabId(formValue.standardPriceVersions[0])"
            message="确定删除当前产品价卡配置？"
            label="删除当前配置"
            byAction
            :delAction="()=>{
            formValue.standardPriceVersions = formValue.standardPriceVersions.filter(tab => getTabId(tab) != activeName);
            activeName = getTabId(formValue.standardPriceVersions[0]);
          }"
        ></ex-button-delete>

        <el-tabs v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0"
                 v-model="activeName" type="card">
          <el-tab-pane v-for="(item,index) in formValue.standardPriceVersions"
                       :label="getTabTitle(item)"
                       :name=" getTabId(item) "
                       :key="item.tabId"
          >
            <insurance_price_cfg ref="insurancePriceCfg"
                                 :priceVersionId="item.id"
                                 :versionStartTimeDisabled="index === 0"
                                 :inputForm="item">
            </insurance_price_cfg>
          </el-tab-pane>
        </el-tabs>

        <div v-else style="padding-left: 100px; display: flex; align-items: center;  color: #d41515; ">
          <i class="el-icon-warning" style="margin-right: 8px;"></i>
          还没添加价卡版本
        </div>

      </div>

    </el-form>

    <div style="position: relative; left: 140px; margin-top: 30px; margin-bottom: 20px;">
      <!-- 提 交 -->
      <el-button type="primary" @click="submitForm()">{{ $tt('label_submit') }}</el-button>
      <!-- 返 回 -->
      <el-button @click="return_page_back()">{{ $tt('label_cancel') }}</el-button>

    </div>

  </div>
</template>
<script>

import router_params from '@/mixin/router_params';
import insurance_price_cfg from '@/component/pms/insurance_price_cfg.vue'

let moduleName = "保险产品"

export default {

  // title: "新增" + moduleName,
  components: {insurance_price_cfg},
  mixins: [router_params],
  data() {

    return {

      "categoryArray": [],
      "categoryCache": {},

      "operateType": "",
      "activeName": "",

      "formValue": {
        "checkedSupplyProductIds": [],
        "disableSkuCategoryIds": [],
        "refCompany": [],
        "standardPriceVersions": [],
      },

      "supplyArr": [],
      "supplyMap": {},
      isEdit: false,

    };
  },

  created() {
    let _this = this
    let editId = this.$route.query.id;
    if (editId) {
      this.isEdit = true
      this.$tag.tagModifyLabel("修改保险产品")
    } else {
      this.$tag.tagModifyLabel("新增保险产品")
    }

    this.$ajax({
      url: '/mms-api/sku/MmsSkuCategoryInfoRpc/allCategory.json',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.categoryArray = res.data.rows
          _this.dfs(_this.categoryArray)
        }

        if (editId) {
          _this.$ajax({
            url: '/fms-api/product/PmsInsuranceProductRpc/detail.json?id=' + editId,
            success: (res) => {
              if (res && res.data) {
                let tmp = res.data
                tmp.checkedSupplyProductIds = tmp.supplyProductList.map(e => e.id + '')
                tmp.disableSkuCategoryIds = tmp.disableSkuCategoryList.map(e => e.skuCategoryIds.map(rr => rr + ''))


                _this.formValue = {..._this.formValue, ...tmp}


                _this.formValue.standardPriceVersions.forEach(r => {
                  r.labelTitle = _this.getTabTitle(r)
                })

                _this.formValue.standardPriceVersions.forEach(r => {
                  if (!r.id) {
                    r.id = 'id_' + (Math.random() + '').replace('.', '')
                  }
                })

                _this.activeName = _this.getTabId(_this.formValue.standardPriceVersions[0])
              }
            }
          });
        }


      }
    });

    this.$ajax({
      url: '/fms-api/product/PmsSupplyProductRpc/selectProductSimple.json?productType=INSURANCE',
      success: (res) => {
        if (res && res.data && res.data.rows) {
          _this.supplyArr = res.data.rows
          _this.supplyArr.forEach(e => {
            _this.supplyMap[e.id] = e
          })
        }
      }
    });


  },

  mounted() {

  },
  methods: {

    adTabConfig() {

      if (!_.isEmpty(this.formValue.standardPriceVersions)){
        let sample = JSON.parse(JSON.stringify(this.formValue.standardPriceVersions[this.formValue.standardPriceVersions.length - 1]))

        let lastTime = sample.versionEndTime

        sample.versionStartTime = lastTime
        sample.versionStartTime = parseInt(lastTime) + 86400000
        sample.versionEndTime = parseInt(lastTime) + 31536000000
        sample.status = 'ENABLE'
        sample.versionId = '-1'

        sample.id = 'id_' + (Math.random() + '').replace('.', '')

        this.formValue.standardPriceVersions.push(sample)
      }else{
        // init

        let firstObj = {}

        let lastTime = new Date().getTime()

          firstObj.versionStartTime = lastTime
          firstObj.versionStartTime = parseInt(lastTime)
          firstObj.versionEndTime = parseInt(lastTime) + 31536000000
          firstObj.status = 'ENABLE'
          firstObj.versionId = '-1'

          firstObj.id = 'id_' + (Math.random() + '').replace('.', '')

          this.formValue.standardPriceVersions.push(firstObj)
      }
      this.activeName = this.getTabId(this.formValue.standardPriceVersions[this.formValue.standardPriceVersions.length - 1])

    },
    getTabTitle(item) {
      return this.$dateFormatDate(item.versionStartTime) + ' 至 ' + this.$dateFormatDate(item.versionEndTime)
    },

    getTabId(item) {
      return 'tab_' + item.id
    },

    submitForm() {

      let _this = this


      this['$refs']['formEl'].validate((valid) => {

        // 服务商
        if (_this.formValue.checkedSupplyProductIds.length == 0) {
          _this.$message({type: 'error', message: '还没有选中保险服务商'})
          return
        }
        let arr = []
        _this.formValue.checkedSupplyProductIds.forEach(e => {
          arr.push(_this.supplyMap[e])
        })
        _this.formValue.supplyProductList = arr

        // sku category
        if (_this.formValue.disableSkuCategoryIds && _this.formValue.disableSkuCategoryIds.length > 0) {

          let arr = []
          _this.formValue.disableSkuCategoryIds.forEach(ids => {

            let names = ids.map(id => _this.categoryCache[id])
            arr.push({
              "skuCategoryIds": ids,
              "skuCategoryNames": names
            })
          })

          _this.formValue.disableSkuCategoryList = arr
        } else {
          _this.formValue.disableSkuCategoryList = []
        }

        // 补充标准价卡数据
        if (_this.formValue.standardPriceVersions && _this.formValue.standardPriceVersions.length > 0) {
          let versions = _this.$refs['insurancePriceCfg'].map(e => e.getFormData())

          this.formValue.standardPriceVersions = versions

        }

        if (valid) {
          this.$ajax({
            url: '/fms-api/product/PmsInsuranceProductRpc/saveUpdate.json',
            type: 'json',
            data: _this.formValue,
            success: (responseData) => {
              this.$message({
                showClose: true,
                message: '提交成功',
                type: 'success'
              })

              this.return_emit(null, "reload")
              this.return_page_back()

            }
          });
        } else {
          return false
        }
      });
    },

    // 递归赋值
    dfs(arr) {
      if (arr) {
        arr.forEach(e => {
          this.categoryCache[e.id] = e.name
          if (e.children) {
            this.dfs(e.children)
          }
        })
      }
    },


    goback() {
      this.$tag.tagClose()
    },


  }
};

</script>
<style>
.product-line-limit-div,
.product-line-limit-div-2 {
  display: flex;
}


.product-line-limit-div .product-line-limit-col {
  width: 220px;
  text-align: center;
  margin-right: 10px;
}

.product-line-limit-div-2 div {
  width: 300px;
  /*text-align: center;*/
  margin-right: 10px;
}

.price-cal-div-row {
  display: flex;
}

.price-cal-div-row .price-cal-col {
  width: 120px;
  text-align: center;
}

.price-cal-div-row div {
  margin-right: 8px;
  text-align: center;
}
</style>
